#!/usr/bin/env python3
"""验证环境安装脚本"""

import sys
import importlib
import pkg_resources

def check_python_version():
    """检查Python版本"""
    required_version = (3, 8)
    current_version = sys.version_info[:2]

    print(f"检查Python版本: ", end="")
    if current_version >= required_version:
        print(f"✓ Python {'.'.join(map(str, current_version))}")
        return True
    else:
        print(f"✗ 需要Python {'.'.join(map(str, required_version))}+，"
              f"当前版本为{'.'.join(map(str, current_version))}")
        return False

def dump_config_info():
    """检查依赖包"""
    core_packages = {
        'jinja2': ('Jinja2', ['markupsafe']),
        'yaml': ('PyYAML', []),
        'sqlparse': ('sqlparse', []),
        'mysql.connector': ('mysql-connector-python', ['protobuf'])
    }

    all_success = True
    print("\n检查核心依赖:")

    for import_name, (pkg_name, sub_deps) in core_packages.items():
        print(f"\n检查 {pkg_name}:")
        try:
            module = importlib.import_module(import_name)
            version = pkg_resources.get_distribution(pkg_name).version
            print(f"  ✓ {pkg_name}: {version}")

            # 检查子依赖
            for sub_dep in sub_deps:
                try:
                    sub_version = pkg_resources.get_distribution(sub_dep).version
                    print(f"    ✓ {sub_dep}: {sub_version}")
                except Exception as e:
                    print(f"    ✗ {sub_dep}: 未安装或版本错误")
                    all_success = False

        except ImportError:
            print(f"  ✗ {pkg_name}: 未安装")
            all_success = False
        except Exception as e:
            print(f"  ✗ {pkg_name}: 错误: {str(e)}")
            all_success = False

    return all_success

def check_optional_dependencies():
    """检查可选依赖"""
    optional_packages = {
        'typing_extensions': ('typing_extensions', []),
        'dateutil': ('python-dateutil', ['six'])
    }

    print("\n检查可选依赖:")
    for import_name, (pkg_name, sub_deps) in optional_packages.items():
        print(f"\n检查 {pkg_name}:")
        try:
            module = importlib.import_module(import_name)
            version = pkg_resources.get_distribution(pkg_name).version
            print(f"  ✓ {pkg_name}: {version}")

            # 检查子依赖
            for sub_dep in sub_deps:
                try:
                    sub_version = pkg_resources.get_distribution(sub_dep).version
                    print(f"    ✓ {sub_dep}: {sub_version}")
                except Exception as e:
                    print(f"    ! {sub_dep}: 未安装或版本错误（可选）")

        except ImportError:
            print(f"  - {pkg_name}: 未安装（可选）")
        except Exception as e:
            print(f"  ! {pkg_name}: 错误: {str(e)}")

def main():
    """主函数"""
    print("=== 妙码环境检查 ===\n")

    python_ok = check_python_version()
    deps_ok = dump_config_info()
    check_optional_dependencies()

    print("\n=== 检查结果 ===")
    if python_ok and deps_ok:
        print("✓ 环境检查通过！可以开始使用妙码。")
        sys.exit(0)
    else:
        print("✗ 环境检查未通过。请解决上述问题后重试。")
        print("\n提示：")
        print("1. 确保已安装所有依赖：pip install -r requirements.txt")
        print("2. 如果安装失败，尝试：pip install -r requirements.txt --no-deps")
        print("   然后：pip install -r requirements.txt")
        print("3. 检查Python版本是否满足要求")
        sys.exit(1)

if __name__ == "__main__":
    main()